<template>
    <div>
        <!-- tree -->
        <a-tree class="myTree" :data="treeData" :fieldNames="{
            key: 'id',
            title: 'name',
            children: 'children',
        }" @select="onSelect">
        </a-tree>
    </div>
</template>

<script setup lang="ts">
import { useVueCesium } from 'vue-cesium'
import type { VcViewerProvider, VcReadyObject, CesiumCartesian2, CesiumCartesian3Array } from 'vue-cesium/es/utils/types'
import { update3dtilesMaxtrix } from "../../utils/update3dtilesMaxtrix";
import scenetree from "./scenetree.json";
import { ref } from 'vue'

const treeData = ref([])
treeData.value = scenetree.scenes[0].children;

const tileset = ref(null)

const $vc: VcViewerProvider = useVueCesium()

$vc.creatingPromise.then((readyObj: VcReadyObject) => {

    console.log(readyObj.viewer) // instanceof Cesium.Viewer
    let Cesium = readyObj.Cesium
    let viewer = readyObj.viewer

    // 加载 3dtiles 模型
    const scene = viewer.scene; // 创建场景

    // 向集合添加一个原语。
    const primitive = scene.primitives.add(
        new Cesium.Cesium3DTileset({
            url: "http://120.27.150.252/sppmodel/1/tileset.json", // 还可以是json、http链接等
            dynamicScreenSpaceError: true,
            cullWithChildrenBounds: false,
            skipLevels: 0,
            maximumScreenSpaceError: 0,
        })
    );

    tileset.value = primitive

    tileset.value.readyPromise
        .then(function (tileset) {
            // 坐标转换和定位
            let params = {
                tx: 117.227267, //模型中心X轴坐标（经度，单位：十进制度）
                ty: 31.820567, //模型中心Y轴坐标（纬度，单位：十进制度）
                tz: 0, //模型中心Z轴坐标（高程，单位：米）
                rx: 0, //X轴（经度）方向旋转角度（单位：度）
                ry: 0, //Y轴（纬度）方向旋转角度（单位：度）
                rz: 0, //Z轴（高程）方向旋转角度（单位：度）
            };
            update3dtilesMaxtrix(tileset, params);
            tileset.style = new Cesium.Cesium3DTileStyle({
                color: {
                    conditions: [["true", 'color("#563624", 0.5)']],
                },
            });

            // 点击高亮元素开始
            const hightLighted = {
                feature: undefined,
                originalColor: new Cesium.Color(),
            };

            viewer.screenSpaceEventHandler.setInputAction(function onLeftClick(event) {
                // 清除之前的高亮元素
                if (Cesium.defined(hightLighted.feature)) {
                    hightLighted.feature.color = hightLighted.originalColor;
                    hightLighted.feature = undefined;
                }

                // 选择新要素
                const pickedFeature = viewer.scene.pick(event.position);
                if (!Cesium.defined(pickedFeature)) {
                    return;
                }

                // 存储选中要素的信息
                hightLighted.feature = pickedFeature;
                Cesium.Color.clone(pickedFeature.color, hightLighted.originalColor);
                // 高亮选中元素
                pickedFeature.color = Cesium.Color.YELLOW;
            }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
            // 点击高亮元素结束

            // Silhouettes are supported
            if (Cesium.PostProcessStageLibrary.isSilhouetteSupported(viewer.scene)) {
                var silhouetteBlue = Cesium.PostProcessStageLibrary.createEdgeDetectionStage();
                silhouetteBlue.uniforms.color = Cesium.Color.BLUE;
                silhouetteBlue.uniforms.length = 0.01;
                silhouetteBlue.selected = [];
                var selected = {
                    feature: undefined,
                    originalColor: new Cesium.Color()
                };
                viewer.scene.postProcessStages.add(Cesium.PostProcessStageLibrary.createSilhouetteStage([silhouetteBlue]));

                var nameOverlay = document.createElement('div');
                viewer.container.appendChild(nameOverlay);
                nameOverlay.className = 'backdrop';
                nameOverlay.style.display = 'none';
                nameOverlay.style.position = 'absolute';
                nameOverlay.style.bottom = '0';
                nameOverlay.style.left = '0';
                nameOverlay.style['pointer-events'] = 'none';
                nameOverlay.style.padding = '4px';
                nameOverlay.style.backgroundColor = 'black';
                nameOverlay.style.color = '#fff';
                // 鼠标移入高亮轮廓开始
                viewer.screenSpaceEventHandler.setInputAction(function onMouseMove(movement) {
                    silhouetteBlue.selected = [];

                    // Pick a new feature
                    var pickedFeature = viewer.scene.pick(movement.endPosition);

                    if (!Cesium.defined(pickedFeature)) {
                        nameOverlay.style.display = 'none';
                        return;
                    }

                    // A feature was picked, so show it's overlay content
                    nameOverlay.style.display = 'block';
                    nameOverlay.style.bottom = viewer.canvas.clientHeight - movement.endPosition.y + 'px';
                    nameOverlay.style.left = movement.endPosition.x + 'px';
                    var name = pickedFeature.getProperty('name');
                    if (!Cesium.defined(name)) {
                        name = pickedFeature.getProperty('id');
                    }
                    nameOverlay.textContent = name;

                    // Highlight the feature if it's not already selected.
                    if (pickedFeature !== selected.feature) {
                        silhouetteBlue.selected = [pickedFeature];
                    }

                }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
                // 鼠标移入高亮轮廓结束
            }

            const default_headingPitchRange = new Cesium.HeadingPitchRange(
                0.3,
                -0.2,
                tileset.boundingSphere.radius * 2.0
            );
            viewer.flyTo(tileset, { offset: default_headingPitchRange });
        })
})

// 点击树节点
const onSelect = (checkedKeys, info) => {
    let id = info.node.id;
    let conditionId = "${id} === " + `"${id}"`;

    tileset.value.style = new Cesium.Cesium3DTileStyle({
        color: {
            conditions: [
                [conditionId, 'color("yellow", 1)'],
                ["true", 'color("#563624", 0.5)'],
            ],
        },
    });
}

</script>

<style scoped>
.myTree {
    position: fixed;
    top: 0px;
    left: 210px;
    border: 1px solid #fff;
    height: 100vh;
    overflow-y: auto;
    z-index: 999;
}

:deep(.arco-tree-node-title-text) {
    color: #fff;
}
</style>